<template>
  <div class="treemap-gadget-css" style="width:100%;height:100%" :id="id">
    <Portal to="right-disable" style="width:100%;height:100%"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="never"
                                  class="aui-card--fill"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                  :style="{height: '100%',border:0}">
        <el-card shadow="never"
                 :style="{height: '100%',border:0}"
                 class="aui-card--fill content-card">
          <div style="width:100%;height:100%;">
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="(widgetName && widgetName.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
              <GadgetTitle :gadgetSetting="gadgetSetting"
                           :widgetName="widgetName"></GadgetTitle>
              <MoreMenu :slicer='slicer'
                        :fitToHeight='fitToHeight'
                        :gadgetId='id'
                        :gadgetType='gadgetInfo.com'
                        @updateQuery="query"
                        :widgetName="widgetName"
                        :businessType="gadgetInfo.businessType"
                        :id="gadgetInfo.id"
                        @showQueryModel="showQueryModel"
                        @fullScreen="fullScreen" />

            </div>
            <div class="control-section control-section2">
              <div class="content-wrapper" style="width:100%;height:100%;">
                <div v-if="isHasData" style="width:100%;height:100%;">
                  <ejs-treemap :id='`container-${key}`'
                               :style="{height:'100%'}"
                               ref='treemap'
                               align="center"
                               :load='load'
                               :tooltipRendering='tooltipRendering'
                               :palette='gadgetSetting.palette'
                               :titleSettings='gadgetSetting.titleSettings'
                               :enableDrillDown='gadgetSetting.enableDrillDown'
                               :useGroupingSeparator='gadgetSetting.useGroupingSeparator'
                               :dataSource='dataSource'
                               :weightValuePath='gadgetSetting.weightValuePath'
                               :tooltipSettings='gadgetSetting.tooltipSettings'
                               :leafItemSettings='gadgetSetting.leafItemSettings'
                               :levels='gadgetSetting.levels'></ejs-treemap>
                </div>
                <div v-else
                      class="gadget-no-newdata">
                    <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <!-- <div class="widgets-tip"> <a :href="widgetNoDataWiki"  :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div> -->
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
        <Lastupdatetime v-if="currentTime"
                        :currentTime="currentTime"
                        :linkedDatasetList="linkedDatasetList"
                        :errorStatus="errorStatus"
                        @updateQuery="query()"></Lastupdatetime>
      </DashboardInterceptConsumer>

    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           :slicer='slicer' />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import { defaultGadgetSettingList } from '@/utils/data-json'
import {v4} from 'uuid'

export default ({
  mixins: [mixinGadgetViewModule],
  components: { Lastupdatetime, model: () => import('@/components/gadget/query-model/query-model') },
  data: function () {
    return {
      dataSource: [],
      currentTime: null,
      gadgetSetting: null,
      loading: false,
      chartWidth: '1280',
      chartHeight: '500',
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'drilldowntreemapgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'drilldowntreemapgadget' }).gadgetSetting
        }
      },
      queryId: '',
      queryDrillthrough: {},
      widgetName: '',
      headerdata: [
        { value: 'Near', text: 'Near' },
        { value: 'Far', text: 'Far' },
        { value: 'Center', text: 'Center' }
      ],
      localFields: { text: 'value', value: 'text' },
      labelswidth: 120,
      linkedDatasetList: [],
      key:v4()
    }
  },

  created () {
    // this.gadgetHeight = (this.gadgetInfo.h * 20) - 45
    this.query()
    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.$store.state.isWidget = false
  },
  methods: {
    tooltipRendering: function (args) {
      if (args.item['groupIndex'] !== 2) {
        args.cancel = true
      }
    },
    changeHeader: function (args) {
      let treemap = this.$refs.treemap.ej2Instances
      for (let i = 0; i < treemap.levels.length - 1; i++) {
        treemap.levels[i].headerAlignment = this.gadgetSetting.headeralignment
      }
      // treemap.refresh()
    },
    changeLabels: function (args) {
      let treemap = this.$refs.treemap.ej2Instances
      treemap.levels[2].headerAlignment = this.gadgetSetting.labelalignment
      // treemap.refresh()
    },
    changeDrillView: function (args) {
      let treemap = this.$refs.treemap.ej2Instances
      treemap.drillDownView = this.gadgetSetting.drilldownview
      // treemap.refresh()
    },
    changebreadCrumb: function (args) {
      // let treemap = this.$refs.treemap.ej2Instances
      this.$refs.treemap.ej2Instances.enableBreadcrumb = this.gadgetSetting.breadcrumb
      // treemap.refresh()
    },
    changebreadCrumbText: function (args) {
      let treemap = this.$refs.treemap.ej2Instances
      let breadCrumbText = document.getElementById('breadCrumbText').value
      treemap.breadcrumbConnector = breadCrumbText
      treemap.refresh()
    },
    itemMove: function (args) {
      args.item['data'].Sales = args.item['weight']
      // eslint-disable-next-line
      args.treemap.tooltipSettings.format = args.item['groupIndex'] === 0 ? `Country: ${args.item.data.Continent}<br>Sales: ${args.item.data.Sales}` : `Country: ${args.item.data.Continent}<br>Company: ${args.item.data.Company}<br>Sales: ${args.item.data.Sales}`
    },
    load () {
      this.treemap = this.$refs.treemap
      // this.gadgetHeight = this.gadgetInfo.h * 20 - 45
      this.changeDrillView()
      this.changebreadCrumb()
      this.changeHeader()
      this.changeLabels()
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      setTimeout(() => {
        this.$refs.treemap.ej2Instances.refresh()
      }, 0)
    },
    containerResizedEvent (i, newH, newW, newHPx, newWPx) {
      this.chartWidth = (newWPx - 5) + 'px'
      this.chartHeight = (newHPx - 5) + 'px'
    },
    query (e) {
      this.gadgetSetting = this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      if (e !== 'auto') {
        this.loading = true
      }
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      this.$interface.reports.getReportDataInfo(param).then(({ data: res }) => {
        _self.verifyHasData(res)
        try {
          _self.$parent.$parent.$parent.$parent.$parent.$parent.selectFields = res.selectFields
        } catch (error) {

        }
        // Set y column type is Number or 0
        if (res.config) {
          _self._.merge(_self.gadgetSetting, res.config)
        }
        if (res.name) {
          _self.widgetName = res.name
        } else if (this.wName) {
            _self.widgetName = this.wName
        } else {
          _self.widgetName = _self.gadgetSetting.headerTitle
        }
        _self.linkedDatasetList = res.datasetSync
        // _self.dataSource = res.data
        if(_self.$refs.treemap){
          _self.$refs.treemap.ej2Instances.dataSource = res.data
        }
        // let tempList = res.data
        // tempList = this.formatData(res.data, res.selectFields).filter(item => item.tenant_name)
        // _self.dataSource = []
        // _self._.uniqBy(JSON.parse(JSON.stringify(tempList)), 'tenamnt_name').forEach(item => {
        //   _self.dataSource.push({ Continent: item })
        // })
        // _self.dataSource.forEach(item => {
        //   var tenamtName = item.Continent.tenant_name
        //   item.Continent = _self._.uniqBy(JSON.parse(JSON.stringify(tempList)), 'user_name').filter(i => i.tenant_name === tenamtName)
        //   item.Continent.forEach(its => {
        //     var userName = its.user_name
        //     its.Name = its.tenant_name
        //     its.States = JSON.parse(JSON.stringify(tempList)).filter(i => i.user_name === userName)
        //   })
        // })
      }).catch((error) => {
          if (this.wName) {
          this.widgetName = this.wName
        }
        this.isHasData = false
        this.loading = false
        if (error.response && error.response.status === 504) {
          this.errorStatus = '504'
          this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
        }
      }).finally(() => {
        this.currentTime = new Date()
        this.autoRefreshQuery(e)
        this.updateGadgetLoadingStatus(!this.loading)
      })
    }
  }
})
</script>
<style lang="scss" scoped>
.content-card {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 45%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}
tr {
  height: 60px;
}
</style>
<style lang="scss">
.treemap-gadget-css {
  .el-card__body {
    width: 100%;
    height: 100%;
  }
  .control-section2 {
    width: 100%;
    height: calc(100% - 34px);
  }
}
</style>
